#json !/usr/bin/env python
#-*- coding:utf-8 -*-
from __future__ import division
import os
import sys
import datetime
reload(sys) 
sys.setdefaultencoding('utf8')
import time
import MySQLdb
import json
import calendar
sys.path.insert(0,'/home/liuyue/svn/wan/')
sys.path.insert(0,'/opt/wanalytics/')
from Tools import connectMySQL




def ChannelDay():
    
    _yesday = datetime.datetime.today() + datetime.timedelta(-1)
    _datetime = _yesday.strftime('%Y%m%d')
    _datesql = " and date = '%s' " % _datetime
    #_datesql = " "
    #数据库连接
    try:
        db = connectMySQL.connMySQL("stat")
    except MySQLdb.Error, e:
        resultStr = '{"status": "failed", "code": "4001", "str": "connect database failed"}'
        return resultStr
    db.autocommit(True)
    c = db.cursor()
    
    json_fix = []
    sql = " SELECT vv_json FROM `channel_day_vv` where vv_json != '{}' and partner_mode in (1,2,3,8)  "
    c.execute(sql)  
    resjson = c.fetchall()
    for vl in resjson:
        strc = str(vl[0])
        arr0 = json.loads(strc)
        for key,value in arr0.items():
            json_fix.append(key)
    json_fix = set(json_fix)
    
    
    sql = " SELECT date FROM `channel_day_vv` WHERE  business_type = 2 and pid_stat = 1 %s group by date " % _datesql
    c.execute(sql)  
    dateres = c.fetchall()
    date_c = []
    for vvl in dateres:
        date_c.append(vvl[0]) 
    
    
    
    os_array = ['-1','61','59','52']
    device_array = ['-1','1','2']
    for os in os_array:
        for device in device_array:
            
            if os == '-1':
                _os = '61,59,52'
            else:
                _os = os
            if device == '-1':
                _device = '1,2'
            else:
                _device = device
                
            for datecc in date_c:
                
                sql = " SELECT date,vv_json FROM `channel_day_vv` WHERE  vv_json != '{}' and  business_type = 2 and pid_stat = 1 and os_id in (%s) and device_type in (%s) and partner_mode in (1,2,3,8) and date = %s  " % (_os,_device,datecc)
                
                c.execute(sql)  
                bresult = c.fetchall()
                            
                str3 = {}
                for x in bresult:
                    vv_json = str(x[1])
                    arr0 = json.loads(vv_json)
                    vv = arr0.keys()
                    for ssc in json_fix:
                        if ssc not in vv:
                            arr0[ssc] = 0
                    for key,value in arr0.items():
                        str3[key] = str3.get(key,0) + value
                print str3,json_fix

                for jfx in json_fix:
                    try:    
                        shu = str3[jfx]
                    except:
                        print 'ok,done'
                        break
                    _name = jfx
                    _dd = datecc
                    sql = " insert into result_channel (`date`,`vv`,`channel`,`os_id`,`device_type`) values ('%s','%s','%s','%s','%s') " % (_dd,shu,_name,os,device)
                    try:
                        c.execute(sql)
                    except Exception,e:
                        c.execute("update result_channel set vv = '%s' where date = %s and channel = '%s' and os_id = '%s' and device_type = '%s' " % (shu,_dd,_name,os,device) )
                        print e
                
                    
                
            
      
    
    c.close()
    db.close()
    
    


    





if __name__ == '__main__':
    cmd = ''
    if len(sys.argv) == 2:
        cmd = sys.argv[1]

    if cmd == 'channel':
        print "ChannelDay()"
        ChannelDay()
    else:
        print "Nothing Happen!"
